package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.TbUser;
import com.bwie.mapper.TbUserMapper;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TbUserServiceImpl implements TbUserService {
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R loginMobile(LoginInfoVo loginInfoVo) {
            //根据手机号查询用户
        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile())
        );
        if (tbUser==null){
            return R.ERROR(500,"用户不存在");
        }
        if (!tbUser.getUserPass().equals(loginInfoVo.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .compact();
        String tokenKey = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,20, TimeUnit.MINUTES);
        tbUser.setToken(token);
        tbUser.setUserPass(null);
        return R.OK(tbUser);
    }

    @Override
    public R getUserById(Integer userId) {
        //根据id查询用户信息
        TbUser tbUser = tbUserMapper.selectById(userId);
        if (tbUser==null){
            return R.ERROR(404,"用户不存在");
        }
        return R.OK(tbUser);


    }
}
